package net.vinote.smart.platform.module.dbpool;

import java.sql.Connection;
import java.sql.SQLException;

import net.vinote.smart.platform.comm.StringFunction;

/**
 * 数据库工厂类,用于获取数据库连接的实例
 * 
 * @author zjw 2011-10-25
 */
public final class DataBasePoolFactory {
	private static DataBasePoolFactory factory = new DataBasePoolFactory();

	DBConnectionPool pool;

	private DataBasePoolFactory() {
		ConnectionParam param = new ConnectionParam();
		param.setDirver(System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_DRIVER));
		param.setUrl(System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_URL));
		param.setUser(System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_USERNAME));
		param.setPassword(System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_PASSWORD));
		String minConNum = System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_MINCONNECT);
		if (StringFunction.isBlank(minConNum)) {
			minConNum = "1";
		}
		param.setMinConnectNum(Integer.valueOf(minConNum));
		String maxConNum = System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_MAXCONNECT);
		if (StringFunction.isBlank(maxConNum)) {
			maxConNum = "5";
		}
		param.setMaxConnectNum(Integer.valueOf(maxConNum));
		String timeout = System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_CONNECTTIMEOUT);
		if (StringFunction.isBlank(timeout)) {
			timeout = "500";
		}
		param.setConnectTimeout(Integer.valueOf(timeout));
		param.setAutoCommit("true".equalsIgnoreCase(System
				.getProperty(ConnectionParam.SYSTEM_CFG_DATABASE_COMMIT)));
		pool = new DBConnectionPool(param);
	}

	public void destroy() {
		pool.release();
	}

	public static DataBasePoolFactory getFactory() {
		return factory;
	}

	public Connection getConnection() {
		try {
			return pool.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
}
